package de.edb.dao;


import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import de.edb.model.User;

public class UserDao extends HibernateDaoSupport {
	

	/**
	 * Creates and saves a {@link User} object.
	 * @param name
	 * @param password
	 * @throws DaoException 
	 */
	public void create(String name, String password) throws DaoException {
		User u = new User(name, password);
		save(u);
	}
	
	
	/**
	 * saves a {@link User} object.
	 * @param user
	 * @return
	 * @throws DaoException
	 */
	public User save(User user) throws DaoException {
		if ((user.getName().isEmpty())||(user.getPassword().isEmpty()))
    	{
    		throw new DaoException("Die Pflichtfelder müssen ausgefüllt werden");
    	} else {
			HibernateTemplate template = getHibernateTemplate();
			template.saveOrUpdate(user);
			return user;
    	}
	}

	/**
	 * returns a single user by its primary db key
	 * 
	 * @param id
	 * @return the User
	 */
	public User findById(int id) {
		HibernateTemplate template = getHibernateTemplate();
		return (User) template.get(User.class, id);
	}
	

	/**
	 * deletes a user object
	 * @param user
	 * @throws DaoException
	 */
	public void delete(User user) throws DaoException {
		HibernateTemplate template = getHibernateTemplate();
		template.delete(user);
	}

	/**
	 * @return all User objects from the database.
	 */
	@SuppressWarnings("unchecked")
	public List<User> findAll() {
		HibernateTemplate template = getHibernateTemplate();
		@SuppressWarnings("rawtypes")
		List results = template.loadAll(User.class);
		return results;
	}
	
	/**
	 * @return User object by name
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<User> findByName(final String keyword) {
		HibernateTemplate template = getHibernateTemplate();
		return (List<User>) template.execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(User.class);
				criteria.add(Restrictions.ilike("name", keyword, MatchMode.EXACT));
				List<User> user = criteria.list();
				return user;
			}
		});
	}

}
